import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttercalcpokers/compontents/built_in.dart';
import 'package:fluttercalcpokers/utils/style_config.dart';

// ignore: must_be_immutable
class RateSelect extends StatefulWidget {
  bool showRateSelect;
  List<Map> rateList;
  final handleDone;
  final userIndex;

  RateSelect(
      {Key key,
      this.showRateSelect,
      this.rateList,
      this.handleDone,
      this.userIndex})
      : super(key: key);

  @override
  _RateSelectState createState() => _RateSelectState();
}

class _RateSelectState extends State<RateSelect> {
  double _initDX = 10.0;
  double _initDY = ScreenUtil().setHeight(300);
  double _gridDX = ScreenUtil().setWidth(50) + 2.0;
  double _gridDY = ScreenUtil().setHeight(40) + 2.0;
  double _dx = 0.0;
  double _dy = 0.0;
  int _tempIndex = 0;
  String selectValue = "";
  bool showCursor = false;

  void delItemFromList() {
    setState(() {
      widget.rateList[_tempIndex]["select"] = false;
    });
  }

  void addItemToList() {
    setState(() {
      widget.rateList[_tempIndex]["select"] = true;
    });
  }

  void moveCursor(int x, int y) {
    int _index_x = _tempIndex % 13 + x;
    int _index_y = _tempIndex ~/ 13 + y;
    _tempIndex = _index_y * 13 + _index_x;
    if (_index_y < 0 || _index_x < 0 || _index_x > 12 || _index_y > 12) {
      return;
    }
    for (int i = 0; i < widget.rateList.length; i++) {
      widget.rateList[i]["isCursor"] = false;
    }
    setState(() {
      showCursor = true;
      widget.rateList[_tempIndex]["isCursor"] = true;
    });
  }

  Future<bool> handleCleanRate() {
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("提示"),
          content: Text("您确定要清空所选范围么吗?"),
          actions: <Widget>[
            FlatButton(
              child: Text("取消"),
              onPressed: () => Navigator.of(context).pop(), //关闭对话框
            ),
            FlatButton(
              child: Text("清空"),
              onPressed: () {
                setState(() {
                  for (int i = 0; i < widget.rateList.length; i++) {
                    widget.rateList[i]["select"] = false;
                  }
                  selectValue = "";
                });
                Navigator.of(context).pop(true); //关闭对话框
              },
            ),
          ],
        );
      },
    );
  }

  void handleDesignClick(context) {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new ListTile(
                leading: new Icon(Icons.photo_camera),
                title: new Text("Camera"),
                onTap: () async {
                  print("1111111");
                },
              ),
              new ListTile(
                leading: new Icon(Icons.photo_library),
                title: new Text("Gallery"),
                onTap: () async {
                  print("object");
                },
              ),
            ],
          );
        });
    return;
  }

  void handleAddJunko() {
    setState(() {
      showCursor = false;
      for (int i = 0; i < widget.rateList.length; i++) {
        if (widget.rateList[i]["isBigJunko"] == true) {
          widget.rateList[i]["select"] = true;
          continue;
        }
      }
    });
  }

  void handleAddPairs() {
    setState(() {
      showCursor = false;
      for (int i = 0; i < widget.rateList.length; i++) {
        if (widget.rateList[i]["isPairs"] == true) {
          widget.rateList[i]["select"] = true;
          continue;
        }
      }
    });
  }

  void handleAddSuit() {
    setState(() {
      showCursor = false;
      for (int i = 0; i < widget.rateList.length; i++) {
        if (widget.rateList[i]["isSuit"] == true) {
          widget.rateList[i]["select"] = true;
          continue;
        }
      }
    });
  }

  void handleAddNotSuit() {
    setState(() {
      showCursor = false;
      for (int i = 0; i < widget.rateList.length; i++) {
        if (widget.rateList[i]["isPairs"] == true) {
          widget.rateList[i]["notSuit"] = true;
          continue;
        }
      }
    });
  }

  void handleBuiltIn() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return BuiltIn(
            addBigJunko: handleAddJunko,
            addAllPairs: handleAddPairs,
            addAllSuit: handleAddSuit,
            addAllNotSuit: handleAddNotSuit,
          );
        });
  }

  @override
  void initState() {
    selectValue = "";
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    BoxDecoration _notCursor(item) {
      return BoxDecoration(
        color: item == true ? Colors.cyanAccent : Colors.white10,
      );
    }

    BoxDecoration _isCursor(item) {
      return BoxDecoration(
        color: item == true ? Colors.cyanAccent : Colors.white10,
        image: DecorationImage(
            image: AssetImage("images/btn.png"), fit: BoxFit.fill),
      );
    }

    Widget itemBuilder(item) {
      return InkWell(
          onTap: () {
            setState(() {
              item["select"] = !item["select"];
            });
          },
          child: Container(
            width: ScreenUtil().setWidth(50),
            height: ScreenUtil().setHeight(40),
            margin: EdgeInsets.only(bottom: 2.0),
            decoration: showCursor == true && item["isCursor"] == true
                ? _isCursor(item["select"])
                : _notCursor(item["select"]),
            child: Center(
              child: Text(
                item["name"],
                style: TextStyle(
                    fontSize: 8.0,
                    color: item["select"] == true
                        ? Colors.black
                        : Colors.cyanAccent),
              ),
            ),
          ));
    }

    Widget tableBuilder() {
      List<Widget> _wrap = [];
      for (int i = 0; i < widget.rateList.length; i++) {
        _wrap.add(itemBuilder(widget.rateList[i]));
      }
      return Wrap(
        spacing: 2.0, // 主轴(水平)方向间距
        runSpacing: 2.0, // 纵轴（垂直）方向间距
        alignment: WrapAlignment.center,
        children: _wrap,
      );
    }

    return Visibility(
      visible: widget.showRateSelect,
      child: Stack(
        children: <Widget>[
          Material(
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {},
                  child: Container(
                      width: ScreenUtil().setWidth(750),
                      height: ScreenUtil().setHeight(100),
                      color: Color.fromRGBO(0, 0, 0, 0.7)),
                ),
                Container(
                  width: ScreenUtil().setWidth(750),
                  height: ScreenUtil().setHeight(1234),
                  color: Colors.black,
                  child: Column(
                    children: <Widget>[
                      Container(
                        width: ScreenUtil().setWidth(750),
                        height: ScreenUtil().setHeight(100),
                        padding: EdgeInsets.all(10.0),
                        child: Flex(
                          direction: Axis.horizontal,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Container(
                                width: ScreenUtil().setWidth(50),
                                height: ScreenUtil().setHeight(100)),
                            Container(
//                            width: ScreenUtil().setWidth(50),
                              height: ScreenUtil().setHeight(100),
                              child: Center(
                                child: Text(
                                    "玩家  " + (widget.userIndex + 1).toString()),
                              ),
                            ),
                            InkWell(
                              onTap: () {
                                selectValue = "";
                                showCursor = false;
                                widget.handleDone(widget.rateList);
                              },
                              child: Container(
                                height: ScreenUtil().setHeight(100),
                                child: Center(
                                  child: Text("完成"),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      Container(
                        width: ScreenUtil().setWidth(750),
                        height: ScreenUtil().setHeight(75),
                        padding: EdgeInsets.all(10.0),
                        alignment: Alignment.centerLeft,
                        child: Text(
                          selectValue,
                          softWrap: true,
                          textAlign: TextAlign.left,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: fontSize_18,
                          ),
                        ),
                      ),
                      GestureDetector(
                        child: Container(
                          padding: EdgeInsets.only(left: 10.0, right: 10.0),
                          child: tableBuilder(),
                        ),
                        onPanDown: (DragDownDetails e) {
                          showCursor = false;
                          //打印手指按下的位置(相对于屏幕)
                          _dx = e.globalPosition.dx;
                          _dy = e.globalPosition.dy;
                          int _index = ((_dy - _initDY) ~/ _gridDY) * 13 +
                              (_dx - _initDX) ~/ _gridDX;
                          print(_index);
                          _tempIndex = _index;
                          setState(() {
                            widget.rateList[_index]["select"] = true;
                          });
                        },
                        //手指滑动时会触发此回调
                        onPanUpdate: (DragUpdateDetails e) {
                          _dx += e.delta.dx;
                          _dy += e.delta.dy;
                          print(_dx);
                          print(_dy);
                          int _index = ((_dy - _initDY) ~/ _gridDY) * 13 +
                              (_dx - _initDX) ~/ _gridDX;
                          if (_tempIndex == 0 && _index == 0) {
                            setState(() {
                              widget.rateList[_index]["select"] = true;
                            });
                            return;
                          }
                          if (_tempIndex != _index) {
                            _tempIndex = _index;
                            setState(() {
                              widget.rateList[_index]["select"] = true;
                              for (int i = 0; i < widget.rateList.length; i++) {
                                if (widget.rateList[i]["select"] == true) {
                                  selectValue +=
                                      widget.rateList[i]["name"] + ",";
                                }
                              }
                            });
                            return;
                          }
                        },
                        onPanEnd: (DragEndDetails e) {},
                      ),
                      panelBuilder(context)
                    ],
                  ),
                )
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget panelBuilder(context) {
    return Container(
      width: ScreenUtil().setWidth(750),
      padding: EdgeInsets.all(10.0),
      child: Row(
        children: <Widget>[
          Container(
            width: ScreenUtil().setWidth(150),
            padding: EdgeInsets.all(10.0),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    handleDesignClick(context);
                  },
                  child: Container(
                    width: ScreenUtil().setWidth(140),
                    height: ScreenUtil().setHeight(75),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage("images/btn.png"),
                          fit: BoxFit.contain),
                      borderRadius: BorderRadius.all(
                        Radius.circular(
                          ScreenUtil().setWidth(5),
                        ),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "花色",
                        style: TextStyle(
                          fontSize: ScreenUtil().setWidth(18),
                          color: Color.fromRGBO(232, 213, 187, 1),
                        ),
                      ),
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    handleBuiltIn();
                  },
                  child: Container(
                    width: ScreenUtil().setWidth(140),
                    height: ScreenUtil().setHeight(75),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage("images/btn.png"),
                          fit: BoxFit.contain),
                      borderRadius: BorderRadius.all(
                        Radius.circular(
                          ScreenUtil().setWidth(5),
                        ),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "内置",
                        style: TextStyle(
                          fontSize: ScreenUtil().setWidth(18),
                          color: Color.fromRGBO(232, 213, 187, 1),
                        ),
                      ),
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    handleCleanRate();
                  },
                  child: Container(
                    width: ScreenUtil().setWidth(140),
                    height: ScreenUtil().setHeight(75),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage("images/btn_disable.png"),
                          fit: BoxFit.contain),
                      borderRadius: BorderRadius.all(
                        Radius.circular(
                          ScreenUtil().setWidth(5),
                        ),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "清空范围",
                        style: TextStyle(
                          fontSize: ScreenUtil().setWidth(18),
                          color: Color.fromRGBO(232, 213, 187, 1),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(400),
            padding: EdgeInsets.all(10.0),
            alignment: Alignment.center,
            child: Column(
              children: <Widget>[
                Container(
                  child: InkWell(
                    onTap: () {
                      moveCursor(0, -1);
                    },
                    child: Container(
                      width: ScreenUtil().setWidth(140),
                      height: ScreenUtil().setHeight(75),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage("images/up.png"),
                            fit: BoxFit.contain),
                        borderRadius: BorderRadius.all(
                          Radius.circular(
                            ScreenUtil().setWidth(5),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Container(
                      child: InkWell(
                        onTap: () {
                          moveCursor(-1, 0);
                        },
                        child: Container(
                          width: ScreenUtil().setWidth(140),
                          height: ScreenUtil().setHeight(75),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage("images/left.png"),
                                fit: BoxFit.contain),
                            borderRadius: BorderRadius.all(
                              Radius.circular(
                                ScreenUtil().setWidth(5),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                    Container(
                      child: InkWell(
                        onTap: () {
                          moveCursor(1, 0);
                        },
                        child: Container(
                          width: ScreenUtil().setWidth(140),
                          height: ScreenUtil().setHeight(75),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage("images/right.png"),
                                fit: BoxFit.contain),
                            borderRadius: BorderRadius.all(
                              Radius.circular(
                                ScreenUtil().setWidth(5),
                              ),
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                Container(
                  child: InkWell(
                    onTap: () {
                      moveCursor(0, 1);
                    },
                    child: Container(
                      width: ScreenUtil().setWidth(140),
                      height: ScreenUtil().setHeight(75),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage("images/down.png"),
                            fit: BoxFit.contain),
                        borderRadius: BorderRadius.all(
                          Radius.circular(
                            ScreenUtil().setWidth(5),
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            width: ScreenUtil().setWidth(150),
            padding: EdgeInsets.all(10.0),
            child: Column(
              children: <Widget>[
                InkWell(
                  onTap: () {
                    addItemToList();
                  },
                  child: Container(
                    width: ScreenUtil().setWidth(140),
                    height: ScreenUtil().setHeight(75),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage("images/btn.png"),
                          fit: BoxFit.contain),
                      borderRadius: BorderRadius.all(
                        Radius.circular(
                          ScreenUtil().setWidth(5),
                        ),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "添加",
                        style: TextStyle(
                          fontSize: ScreenUtil().setWidth(18),
                          color: Color.fromRGBO(232, 213, 187, 1),
                        ),
                      ),
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    addItemToList();
                  },
                  child: Container(
                    width: ScreenUtil().setWidth(140),
                    height: ScreenUtil().setHeight(75),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage("images/btn.png"),
                          fit: BoxFit.contain),
                      borderRadius: BorderRadius.all(
                        Radius.circular(
                          ScreenUtil().setWidth(5),
                        ),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "添加+",
                        style: TextStyle(
                          fontSize: ScreenUtil().setWidth(18),
                          color: Color.fromRGBO(232, 213, 187, 1),
                        ),
                      ),
                    ),
                  ),
                ),
                InkWell(
                  onTap: () {
                    delItemFromList();
                  },
                  child: Container(
                    width: ScreenUtil().setWidth(140),
                    height: ScreenUtil().setHeight(75),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage("images/btn_disable.png"),
                          fit: BoxFit.contain),
                      borderRadius: BorderRadius.all(
                        Radius.circular(
                          ScreenUtil().setWidth(5),
                        ),
                      ),
                    ),
                    child: Center(
                      child: Text(
                        "移除",
                        style: TextStyle(
                          fontSize: ScreenUtil().setWidth(18),
                          color: Color.fromRGBO(232, 213, 187, 1),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}
